import { Button, Checkbox, ConfigProvider, Form, Input } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useIntl } from 'react-intl'
import style from '../index.module.scss'
import AppLocal from '@/assets/lang'
import { Login } from '@/api/user'
import { onLogin } from '@/store/modules/login'
import { useDispatch, useSelector } from 'react-redux'

const FormCom = () => {
  const dispatch = useDispatch()
  const navigator = useNavigate() // 路由跳转
  /*
    结束成功事件：
  */
  const onFinish = async (values: any) => {
    const { username, password } = values
    try {
      const { code, refresh_token, access_token } = await Login({
        name: username,
        password,
      })
      console.log('🌺👉 请求成功==》', code, refresh_token, access_token)
      localStorage.setItem('accessToken', access_token) // 存储access_token到localStorage
      sessionStorage.setItem('refreshToken', refresh_token) // 存储refresh_token到localStorage
      // 登录成功后，跳转到首页
      navigator('/Layout/Home')
    } catch (error) {
      console.log('🌺👉 登录失败==》')
    }

    // try {
    //   const { code, refresh_token, access_token } = await dispatch(
    //     onLogin({ name: username, password }) as any,
    //   )
    //   console.log('🌺👉 打印结果login==》', code, { name: username, password })
    //   navigator('/Layout/Home')
    // } catch (error) {
    //   console.log('登录失败', error)
    // }
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('结束事件:', errorInfo)
  }

  /*
    密码验证规则：
    1. 长度在6-64位之间
    2. 必须包含大小写字母和数字
  */
  const passwordValidator = (_: any, value: any) => {
    if (!value) {
      return Promise.reject(
        `${intl.formatMessage({ id: 'homePage.changePassword.noOldPassword' })}`,
      )
    } else if (value && value.length > 0 && value.length < 6) {
      return Promise.reject(
        `${intl.formatMessage({ id: 'homePage.changePassword.noLength' })}`,
      )
    } else if (value.length > 64) {
      return Promise.reject(
        `${intl.formatMessage({ id: 'homePage.changePassword.lengthTooLong' })}`,
      )
    } else {
      return Promise.resolve()
    }
  }
  /*
    用户名验证规则：
    1. 必须包含大小写字母和数字
    2. 长度在5-32位之间
  */
  const patternName = /^[A-Za-z0-9]+$/
  const usernameValidator = (_: any, value: any) => {
    if (!value) {
      return Promise.resolve() // 如果值为空，通过验证
    }
    if (!patternName.test(value)) {
      return Promise.reject(
        `${intl.formatMessage({ id: 'account.userList.addUserRule1' })}`,
      )
    }
    if (value.length < 5) {
      return Promise.reject(
        `${intl.formatMessage({ id: 'account.userList.addUserRule' })}`,
      )
    }
    if (value.length > 32) {
      return Promise.reject(
        `${intl.formatMessage({ id: 'account.userList.addUserRule3' })}`,
      )
    }
    return Promise.resolve()
  }
  const intl = useIntl()
  const greeting = AppLocal.zh_CN.messages

  return (
    <div className={style.formStyle}>
      <Form
        name="basic"
        wrapperCol={{ span: 18 }}
        initialValues={{
          remember: true,
          username: 'admin',
          password: 'lzno1root',
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'account.userList.inputUsername',
              }),
            },
            {
              validator: (_, value) => usernameValidator(_, value),
            },
          ]}
        >
          <Input
            style={{ width: '300px' }}
            prefix={<UserOutlined />}
            placeholder={intl.formatMessage({
              id: 'loginPage.password.inputUsername',
            })}
            value={'admin'}
            allowClear
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            {
              validator: (_, value) => passwordValidator(_, value),
            },
          ]}
        >
          <Input.Password
            style={{ width: '300px' }}
            prefix={<LockOutlined />}
            placeholder={intl.formatMessage({
              id: 'loginPage.password.inputPassword',
            })}
            allowClear
          />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 0, span: 16 }}
        >
          <Checkbox>
            <div style={{ width: '200px' }}>
              {intl.formatMessage({ id: 'loginPage.password.remember' })}
            </div>
          </Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            {intl.formatMessage({ id: 'loginPage.password.Entersystem' })}
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default FormCom
